﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Vowei.Data;
using Vowei.Core.Models;
using System.Text.RegularExpressions;
using Vowei.Data.Models;
using Vowei.Data.Helpers;
using Vowei.Web.Helpers;
using Vowei.Web;

namespace vowei.web.Controllers
{
    public class RoleController : G18nController
    {
        private IVoweiContext _context;

        public RoleController(IVoweiContext context)
        {
            _context = context;
        }

        public ActionResult Index()
        {
            ViewBag.Roles = Roles.GetAllRoles();

            return View();
        }

        // TODO: 实现权限集和权限的混合分配模式
        public ActionResult Create()
        {
            ViewBag.PermissionSet = _context.PermissionSet.Query.ToArray();
            return View();
        }

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            var name = collection["RoleName"];
            if (Roles.RoleExists(name))
            {
                throw new ArgumentException(
                    string.Format(T("要创建的用户组: {0} 已经存在"), name));
            }

            Roles.CreateRole(name);
            var psidRaw = collection["Permission"];
            var psid = Guid.Parse(psidRaw);
            var ps = _context.PermissionSet.Find(psid);
            var ace = new Ace()
            {
                RoleName = name
            };

            ace.AddPermission(ps);
            _context.Acl.Add(ace);

            _context.SaveChanges();

            return RedirectToAction("AddUser", "Role", new { role = name });
        }

        public ActionResult Delete(string role)
        {
            if (!Roles.RoleExists(role))
            {
                throw new ArgumentException(
                    string.Format(T("用户组: {0} 不存在"), role));
            }

            var acl = _context.Acl.Query.Where(a => a.RoleName == role);
            if (acl.Count() > 0)
            {
                foreach (var ace in acl)
                    _context.Acl.Remove(ace);
            }

            _context.SaveChanges();

            Roles.DeleteRole(role);

            return RedirectToAction("Index");
        }

        public ActionResult Edit(string role)
        {
            if (!Roles.RoleExists(role))
            {
                throw new ArgumentException(
                    string.Format(T("用户组: {0} 不存在"), role));
            }

            ViewBag.Users = Roles.GetUsersInRole(role);
            ViewBag.RoleName = role;

            var permissions = _context.PermissionSet.Query.ToArray();
            var acl = _context.Acl.Query.Where(
                a => a.RoleName == role).ToArray();

            ViewBag.Permissions = new Dictionary<Permission, bool>(new PermissionEqualityComparer());
            foreach (var permission in permissions)
            {
                ViewBag.Permissions[permission] = false;
            }
            foreach (var ace in acl)
            {
                foreach (var permission in ace.Permissions)
                {
                    ViewBag.Permissions[permission] = true;
                }
            }

            return View();
        }

        [HttpPost]
        public ActionResult Edit(FormCollection collection)
        {
            var origName = collection["OriginalRoleName"];
            var newName = collection["RoleName"];
            if (!Roles.RoleExists(origName))
            {
                throw new ArgumentException(
                    string.Format(T("用户组: {0} 不存在"), origName));
            }

            var psidRaw = collection["Permission"];
            var psid = Guid.Parse(psidRaw);
            var ps = _context.PermissionSet.Find(psid);
            var ace = new Ace()
            {
                RoleName = newName
            };
            ace.AddPermission(ps);

            _context.Acl.Add(ace);

            _context.SaveChanges();

            return RedirectToAction("AddUser", "Role", new { role = newName });
        }
               
        public ActionResult AddUser(string role)
        {
            if (string.IsNullOrEmpty(role))
                throw new ArgumentNullException(T("需要指定用户组名称！"));

            ViewBag.UserGroupName = role;
            ViewBag.UserGroupValue = role;
            return View();
        }

        [HttpPost]
        public ActionResult AddUser(FormCollection collection)
        {
            var roleName = collection["RoleName"];
            if (string.IsNullOrEmpty(roleName) || !Roles.RoleExists(roleName))
            {
                throw new ArgumentException(
                    string.Format(T("用户组: {0} 不存在"), roleName));
            }

            var usersRaw = collection["UserEmails"];
            var users = EditingHelpers.SplitUsers(roleName);
            foreach (var userRaw in users)
            {
                var user = userRaw.Trim();
                if ( string.IsNullOrEmpty(user) )
                    continue;

                if (!EntityHelpers.MatchUserEmail(user))
                {
                    throw new ArgumentException(string.Format(T(
                        "输入的电子邮件:{0}不是一个合法的电子邮件地址！"), user));
                }

                Roles.AddUserToRole(user, roleName);
            }

            return RedirectToAction("Edit", new { role = roleName });
        }

        [HttpPost]
        public ActionResult RemoveUser(FormCollection collection)
        {
            var roleName = collection["RoleName"];
            if (string.IsNullOrEmpty(roleName) || !Roles.RoleExists(roleName))
            {
                throw new ArgumentException(
                    string.Format(T("用户组: {0} 不存在"), roleName));
            }

            var usersRaw = collection["UserEmails"];
            if (string.IsNullOrEmpty(usersRaw))
                throw new ArgumentNullException(string.Format(T("请输入要从用户组：{0}删除的用户名"), roleName));

            var users = usersRaw.Split(';', ',');
            foreach (var userRaw in users)
            {
                var user = userRaw.Trim();
                if (string.IsNullOrEmpty(user))
                    continue;

                if (!EntityHelpers.MatchUserEmail(user))
                {
                    throw new ArgumentException(string.Format(T(
                        "输入的电子邮件:{0}不是一个合法的电子邮件地址！"), user));
                }

                Roles.RemoveUserFromRole(user, roleName);
            }

            return RedirectToAction("Edit", new { role = roleName });
        }
    }
}
